import React, { Component } from 'react';
import history from '@/history';
import axios from 'axios'
import './index.less';
import { Input, AutoComplete, message } from 'antd';

import utils from '@/utils/utils'
var timer = null

const SearchIpt = Input.Search;
const Option = AutoComplete.Option;
export default class Search extends Component {
  static displayName = 'Search';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      keyWord: '',
      dataSource: [],
    };

  }

  searchBmjc(val) {
    var keylast = utils.stripscript(val)
    var key = keylast.replace(/\s+/g, "")
    // console.log(key);

    clearTimeout(timer);
    const that = this;
    timer = setTimeout(function () {

      if (key && /^[A-Za-z0-9]{6}$/g.test(key)) {
        // 六位开票代码
        that.getCodeList(key, 0);
      } else if (/[\u4e00-\u9fa5]+/i.test(key) && key.length > 1) {
        // 文字检索
        that.getCodeTextList(key, 0);
      } else {
        that.setState({
          dataSource: []
        })
      }
    }, 200)
  }
  getCodeList(val, type) {
    window._hmt.push(["_trackEvent", `bcard_index_code`, "click", `首页页通过六位代码搜索`]);
    axios.get('/nuonuo/invoice/base/commonInvoice/getkpinfobycode.action', {
      params: {
        intr: val
      }
    }).then(res => {
      if (res.code === 'S0000') {
        if (res.result !== null) {
          // console.log(res.result)
          let TEMP_APPX = {};
          TEMP_APPX.c_code = res.result.barcode
          TEMP_APPX.c_kpcode = res.result.ckpcode
          TEMP_APPX.c_kpname = res.result.ckpname
          TEMP_APPX.signid = res.result.signid
          TEMP_APPX.isCode = 'true'
          if (type === 1) {
            this.jump('', res.result.ckpcode);
            return false;
          }
          this.setState({
            dataSource: [TEMP_APPX]
          })
        } else {
          if (type === 1) {
            this.jump();
            return false;
          }
          message.warning('获取数据异常，稍后再试')
        }
      } else if (res.code === 'S01') {
        message.warning('请登录后进行搜索操作')
      } else {
        if (type === 1) {
          this.jump();
          return false;
        }
        this.setState({
          dataSource: []
        })
      }

    })
  }
  getCodeTextList(val, type) {
    window._hmt.push(["_trackEvent", `bcard_index_text`, "click", `首页页通过模糊匹配搜索`]);
    axios.post('/nuonuo/invoice/base/commonInvoice/login/findInvoiceInfo.action', { intr: val })
      .then(res => {
        if (res.code === 'S0000') {
          if (res.result !== null) {
            if (type === 1) {
              this.jump(res.result.c_code, '');
              return false;
            }
            this.setState({
              dataSource: res.result
            })

          } else {
            // message.warning('未搜索到数据');
            if (type === 1) {
              this.jump();
              return false;
            }
            this.setState({
              dataSource: []
            })
          }
        } else {
          this.setState({
            dataSource: []
          })
          if (res.result === 'S0105') {
            message.warning('请登录后进行搜索操作');
            this.setState({
              dataSource: []
            })
          } else {
            message.warning('获取数据异常，稍后再试')

          }
        }
      })
  }
  onSelect(value, option) {
    // console.log('onSelect', value, option.props, option.props.type);
    if (option.props.type) {
      this.jump('', option.props.kpcode)
    } else {
      this.jump(value, '')
    }
    window._hmt.push(["_trackEvent", `bcard_index_select`, "click", `首页用户点击备选搜索`]);
  }
  jump(kpdm, cpcode) {

    window._hmt.push(["_trackEvent", `bcard_index_select`, "click", `首页用户点击备选搜索`]);
    if (kpdm) {
      history.push({

        // pathname: '/Contents/pages/BCard/index.html/search',
        pathname: 'search',
        search: '?kpdm=' + kpdm
      })
    } else if (cpcode) {
      history.push({
        // pathname: '/Contents/pages/BCard/index.html/search',
        pathname: 'search',
        search: '?kpcode=' + cpcode
      })
    } else {
      history.push({
        // pathname: '/Contents/pages/BCard/index.html/search',
        pathname: 'search',
        search: '?hasData=false'
      })
    }

  }
  onSearch(key) {
    // console.log('onSearch', value);
    // console.log(window._hmt);
    if (key && /^[A-Za-z0-9]{6}$/g.test(key)) {
      // 六位开票代码
      this.getCodeList(key, 1);
      window._hmt.push(["_trackEvent", `bcard_index`, "click", `首页用户点击搜索`]);
    } else if (key.length > 1) {
      // 文字检索
      this.getCodeTextList(key, 1);
      window._hmt.push(["_trackEvent", `bcard_index`, "click", `首页用户点击搜索`]);
    } else {
      this.setState({
        dataSource: []
      })
    }

  }
  renderOption(item) {
    // console.log(item)
    return (
      <Option key={item.c_code} signid={item.signid} kpcode={item.c_kpcode} type={item.isCode}>
        <a>
          {item.c_kpname}
        </a>
      </Option>
    );
  }

  render() {
    const { dataSource } = this.state;


    return (
      <div>
        <div className="search">
          <div className="tab-main">
            <div className="search-container">
              <div className="global-search-wrapper" style={{ width: 560 }}>
                <AutoComplete
                  className="global-search"
                  size="large"
                  style={{ width: '100%' }}
                  dataSource={dataSource.map(this.renderOption)}
                  onSelect={(value, option) => this.onSelect(value, option)}
                  onSearch={value => this.searchBmjc(value)}
                  // onSearch={value => this.onSearch(value)}
                  placeholder="输入企业名称查询"
                  optionLabelProp="text"
                >
                  <SearchIpt
                    enterButton="搜索"
                    maxLength={50}
                    onSearch={value => this.onSearch(value)}
                    size="large"
                  />
                </AutoComplete>
              </div>
            </div>
          </div>
        </div>

      </div>

    );
  }
}
